package com.ruoyi.releation.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.releation.domain.People;
import com.ruoyi.releation.domain.Releation;
import com.ruoyi.releation.service.IPeopleService;
import com.ruoyi.system.domain.SysUser;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/people")
public class PeopleController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(PeopleController.class);
    
    private String prefix = "people";

    @Autowired
    private IPeopleService peopleService;

    @RequiresPermissions("system:people:view")
    @GetMapping()
    public String people()
    {
        return prefix + "/people";
    }

    @RequiresPermissions("system:people:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(People people)
    {
        startPage();
        List<People> list = peopleService.selectPeopleList(people);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:people:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(People people)
    {
        List<People> list = peopleService.selectPeopleList(people);
        ExcelUtil<People> util = new ExcelUtil<People>(People.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:people:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<People> util = new ExcelUtil<People>(People.class);
        List<People> peopleList = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getLoginName();
        String message = peopleService.importUser(peopleList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @RequiresPermissions("system:people:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<People> util = new ExcelUtil<People>(People.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("peoples", peopleService.selectPeopleList(new People()));
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:people:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated People people)
    {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(peopleService.checkNameUnique(people.getName())))
        {
            return error("新增用户'" + people.getName() + "'失败，登录账号已存在");
        }
        people.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(peopleService.insertPeople(people));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        mmap.put("people", peopleService.selectPeopleById(id));
        mmap.put("peoples", peopleService.selectPeopleList(new People()));
        return prefix + "/edit";
    }
    
    /**
     * 修改头像
     */
    @GetMapping("/avatar")
    public String avatar(ModelMap mmap)
    {
        SysUser user = ShiroUtils.getSysUser();
        mmap.put("people", peopleService.selectPeopleByName(user.getUserName()));
        return prefix + "/avatar";
    }
    
    /**
     * 保存头像
     */
    @Log(title = "修改头像", businessType = BusinessType.UPDATE)
    @PostMapping("/updateAvatar")
    @ResponseBody
    public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file)
    {
        SysUser currentUser = ShiroUtils.getSysUser();
        People people = peopleService.selectPeopleByName(currentUser.getUserName());
        try
        {
            if (!file.isEmpty())
            {
                String avatar = FileUploadUtils.upload(Global.getAvatarPath(), file);
                people.setAvatar(avatar);
                if (peopleService.updatePeople(people) > 0)
                {
                    return success();
                }
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("修改头像失败！", e);
            return error(e.getMessage());
        }
    }
    
    @GetMapping("/profile/{id}")
    public String profile(@PathVariable("id") Long id, ModelMap mmap)
    {
        SysUser user = ShiroUtils.getSysUser();
        mmap.put("people", peopleService.selectPeopleByName(user.getUserName()));
        mmap.put("peoples", peopleService.selectPeopleList(new People()));
        return prefix + "/profile";
    }
    
    @GetMapping("/releation")
    public String releation(ModelMap mmap)
    {
        SysUser user = ShiroUtils.getSysUser();
        mmap.put("people", peopleService.selectPeopleByName(user.getUserName()));
        return prefix + "/releation";
    }
    
    /**
     * 获取所有人员
     */
    @GetMapping("/getPeoples")
    @ResponseBody
    public AjaxResult getPeoples()
    {
        List<People> peoples = peopleService.selectPeopleList(new People());
        List<Releation> releations = peopleService.selectReleationList();
        return AjaxResult.success().put("peoples", peoples).put("releations", releations);
    }
    /**
     * 保存头像
     */
    @GetMapping("/getReleations")
    @ResponseBody
    public List<Releation> getReleations()
    {
        return peopleService.selectReleationList();
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:people:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated People people)
    {
        people.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(peopleService.updatePeople(people));
    }


    @RequiresPermissions("system:people:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        try
        {
            return toAjax(peopleService.deletePeopleByIds(ids));
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }
    
    /**
     * 校验用户名
     */
    @PostMapping("/checkNameUnique")
    @ResponseBody
    public String checkNameUnique(People people)
    {
        return peopleService.checkNameUnique(people.getName());
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:people:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(People people)
    {
        return toAjax(peopleService.changeStatus(people));
    }
    
    @RequiresPermissions("system:people:list")
    @PostMapping("/releationList")
    @ResponseBody
    public TableDataInfo releationList(Releation releation)
    {
        startPage();
        List<Releation> list = peopleService.selectReleationList(releation);
        return getDataTable(list);
    }
    
    @GetMapping("/peopleReleation/{id}")
    public String peopleReleation(@PathVariable("id") Long id,ModelMap mmap)
    {
        Releation releation = new Releation();
        releation.setFromId(id);
        mmap.put("people", peopleService.selectPeopleById(id));
        mmap.put("releation", releation);
        return prefix + "/peopleReleation";
    }
    
    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:people:edit")
    @Log(title = "添加关系", businessType = BusinessType.UPDATE)
    @PostMapping("/addReleation")
    @ResponseBody
    public AjaxResult addReleation(@Validated Releation releation)
    {
        return toAjax(peopleService.addReleation(releation));
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:people:edit")
    @Log(title = "删除关系", businessType = BusinessType.UPDATE)
    @PostMapping("/delReleation")
    @ResponseBody
    public AjaxResult delReleation(@Validated Releation releation)
    {
        return toAjax(peopleService.delReleation(releation));
    }
}